package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.utils.StringUtils;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.vo.request.AutoCallReqVo;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.AutoCall;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author cwj
 * @description
 * @date 2024/12/18 11:54
 **/
@Slf4j
@Service
public class AutoCallService extends BaseService<AutoCall> {

    @Resource
    private KafkaService kafkaService;

    @Resource
    private RedisClusterService redisClusterService;

    @Resource
    private DeviceService deviceService;


    /**
     * @description 查询自动接听电话设置信息
     * @author cwj
     * @param [imei]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/12/18 13:29
     **/
    public ResponseMap queryAutoCall(String imei) {
        AutoCall autoCall = queryAutoCallByImei(imei);
        List<Map<String,Object>> contacts = deviceService.obtainContact(imei);
        if(CollectionUtils.isEmpty(contacts)){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(),"API.request.result.noData");
        }
        ResponseMap res = ResponseMap.success();
        res.put("autoCallStatus",ObjectUtils.isEmpty(autoCall)?0:ObjectUtils.isEmpty(autoCall.getAutoCallStatus())?0:autoCall.getAutoCallStatus());
        //设置自动接听的状态
        if(!ObjectUtils.isEmpty(autoCall) && autoCall.getAutoCallStatus().equals(1) && !StringUtils.isEmpty(autoCall.getPhones())){
            String[] phones = autoCall.getPhones().split(",");
            for(int i=0;i<phones.length;i++){
                for(int j=0;j<contacts.size();j++){
                    Map<String,Object> map = contacts.get(j);
                    if(phones[i].equals(map.get("phone"))){
                        map.put("selected",1);
                    }
                }
            }
        }
        res.put("contacts",contacts);
        return res;
    }


    /**
     * @description 设置自动接听电话
     * @author cwj
     * @param [imei, vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/12/18 13:29
     **/
    public ResponseMap settingAutoCall(String imei, AutoCallReqVo vo){
        if(vo.getAutoCallStatus().equals(1) && StringUtils.isEmpty(vo.getPhones())){
            return ResponseMap.fail(ResponseEnum.STATUS400.getCode(), ResponseEnum.STATUS400.getMsg());
        }
        //检查设备是否在线，不在线不能下发
        String onlineStatus = redisClusterService.hget(imei, ConstCacheField.ONLINE_STATUS);
        if (!"1".equals(onlineStatus)) {
            return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
        }
        //保存或更新指令
        updataOrSaveAutoCall(imei, vo);
        // 下发修改代收短信开关的指令
        JSONObject kafkaJson = new JSONObject();
        kafkaJson.put("autoCallStatus", vo.getAutoCallStatus());
        if(vo.getAutoCallStatus().equals(1)){
            kafkaJson.put("phones",vo.getPhones());
        }
        kafkaService.emitDeviceDemand(imei, ConstKafka.DEV_AUTO_CALL, kafkaJson,vo.getOpenid());
        return ResponseMap.success();
    }

    /**
     * @description 保存或更新指令，每个设备只存一条
     * @author cwj
     * @param [imei, vo]
     * @return void
     * @date @time 2024/12/18 13:50
     **/
    private void updataOrSaveAutoCall(String imei, AutoCallReqVo vo) {
        AutoCall autoCall = queryAutoCallByImei(imei);
        Date date = new Date();
        if(ObjectUtils.isEmpty(autoCall)){
            autoCall = new AutoCall();
            autoCall.setImei(imei);
            if(!StringUtils.isEmpty(vo.getPhones())){
                autoCall.setPhones(vo.getPhones());
            }
            autoCall.setAutoCallStatus(vo.getAutoCallStatus());
            autoCall.setCreateTime(DateUtil.getDate(date));
            autoCall.setUpdateTime(DateUtil.getDate(date));
            this.save(autoCall);
        }else{
            //更新设备的cmsgStatus状态，无需多查一次
            Update autoCallUpdate = new Update();
            autoCallUpdate.set("autoCallStatus", vo.getAutoCallStatus());
            if(!StringUtils.isEmpty(vo.getPhones())){
                autoCallUpdate.set("phones", vo.getPhones());
            }
            autoCallUpdate.set("updateTime",DateUtil.getDate(date));
            this.updateById(new ObjectId(autoCall.getId()),autoCallUpdate);
        }
    }

    /**
     * @description 根据imei查询自动接听设置
     * @author cwj
     * @param [imei]
     * @return com.iot08.common.entity.app.AutoCall
     * @date @time 2024/12/18 15:43
     **/
    public AutoCall queryAutoCallByImei(String imei) {
        Query query = new Query(Criteria.where("imei").is(imei));
        query.with(Sort.by(Sort.Order.desc("createTime"))).limit(1);
        return this.findOne(query);
    }
}
